import { has } from 'lodash-es'
import type { MockMethod } from 'vite-plugin-mock'

import {
  mockDateUnix,
  resultError,
  resultPageSuccess,
  resultSuccess
} from './_util'

const userInfo = {
  id: '@id',
  name: 'Ervin Howell',
  username: 'Antonette',
  email: '@email',
  address: '@county(true)',
  phone: '010-692-6593 x09125',
  website: '@domain',
  lastIp: '@ip',
  description: '@paragraph'
}

const dataSource = Array.from({ length: 297 }, () => ({
  _: '@increment',
  id: '@id',
  name: '@name',
  username: '@name',
  email: '@email',
  address: '@county(true)',
  phone: '010-692-6593 x09125',
  website: '@domain',
  lastIp: '@ip',
  description: '@paragraph',
  created_at: mockDateUnix(),
  last_login_at: mockDateUnix()
}))

type IUserModel = typeof userInfo
export default [
  {
    method: 'post',
    url: '/mock/auth/sign-in',
    statusCode: 200,
    response: ({ body }: any) => {
      const res = {
        token:
          'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NzUwNjIwMjksImp0aSI6IjFAMTU5NjA0MjUxNTQ2OTgzMjE5MiJ9.BcLHC0Vhks8EZTGU0znOr2vRNAL9OEJTKquVhx8G7iQ',
        userInfo
      }
      if (has(body, 'password') && has(body, 'account')) {
        return body.account === 'test001' && body.password === 'abcd.1234'
          ? resultSuccess(res)
          : resultError('请输入正确账号/密码')
      }
      if (has(body, 'email') && has(body, 'code')) {
        return body.email === 'test001@gmail.com' && body.code === '937662'
          ? resultSuccess(res)
          : resultError('请输入正确邮箱/验证码')
      }
      return resultError('请输入正确账号/密码')
    }
  },
  {
    method: 'get',
    url: '/mock/user/info',
    statusCode: 200,
    response: () => resultSuccess(userInfo)
  },
  {
    method: 'get',
    url: '/mock/user/list',
    statusCode: 200,
    response: ({
      query
    }: {
      query: { keywords?: string; offset?: number; limit?: number }
    }) => {
      const predicate = ({ id, username, email }: IUserModel) => {
        return (
          id.indexOf(query.keywords!) > -1 ||
          username.indexOf(query.keywords!) > -1 ||
          email.indexOf(query.keywords!) > -1
        )
      }
      const res = query?.keywords ? dataSource.filter(predicate) : dataSource
      return resultPageSuccess(
        Number(query?.offset ?? 0),
        Number(query?.limit ?? 10),
        res
      )
    }
  }
] as MockMethod[]
